package Aleehot100;

import C017.main;

/**
 * ClassName: c028
 * Package: Aleehot100
 * Description: 两数相加(链表形式) - 2
 *
 * @Author BCXJ
 * @Create 2025/6/13 21:36
 * @Version 1.0
 * @Since 1.0
 */
public class c028 {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(9);
        ListNode listNode2 = new ListNode(9);
        ListNode listNode3 = new ListNode(9);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        ListNode listNode11 = new ListNode(9);
        ListNode listNode12 = new ListNode(9);
        ListNode listNode13 = new ListNode(9);
        ListNode listNode14 = new ListNode(9);
        listNode11.next = listNode12;
        listNode12.next = listNode13;
        listNode13.next = listNode14;
       // ListNode listNode = addTwoNumbers(listNode1, listNode11);
        ListNode listNode = addTwoNumbers(listNode11, listNode1);



    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
            next = null;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 健壮性判断
        if(l1 == null || l2 == null) {
            return l1 != null ? l1 : l2;
        }
        ListNode res = null, pre = null;
        ListNode h1 = l1, h2 = l2;
        int add = 0; // 进位
        int val1, val2, addRes;
        while(h1 != null && h2 != null) {
            val1 = h1.val;
            val2 = h2.val;
            addRes = val1 + val2 + add;
            add = addRes / 10;
            addRes = addRes % 10;
            if(res == null) {
                res = new ListNode(addRes);
                pre = res;
            } else {
                pre.next = new ListNode(addRes);
                pre = pre.next;
            }
            h1 = h1.next;
            h2 = h2.next;
        }

        // 一位空了
        while(h1 != null) {
            addRes = h1.val + add;
            add = addRes / 10;
            addRes = addRes % 10;
            pre.next = new ListNode(addRes);
            pre = pre.next;
            h1 = h1.next;
        }

        while(h2 != null) {
            addRes = h2.val + add;
            add = addRes / 10;
            addRes = addRes % 10;
            pre.next = new ListNode(addRes);
            pre = pre.next;
            h2 = h2.next;
        }

        if(add != 0) {
            pre.next = new ListNode(add);
        }
        return res;
    }


    
}
